var self = null;
cc.Class({
    extends: cc.Component,

    properties: {
        tips: cc.Node,
        //普通排行的layout容器节点
        content: cc.Node,

        top1: cc.Node,
        top2: cc.Node,
        top3: cc.Node,

        rankScrollView: cc.ScrollView,

        //玩家自己的数据
        rankMine: cc.Node,
        
        //排行节点
        rankList: cc.Node,
        //超越好友的节点
        beyond: cc.Node,

        //超越好友相关显示信息
        gap: cc.Label,
        beyondHim: cc.Label,
        avatar: cc.Sprite,

        ti: cc.Prefab,

        //滚动排行榜相关
        spawnCount: 24, // 实际创建的项数量
        //totalCount: 0, // 在列表中显示的项数量
        spacing: 0, // 项之间的间隔大小
        updateInterval: 0.5//更新间隔
    },

    start(){
        self = this;
        self.rankList.active = false;
        self.beyond.active = false;
        self.avatar.imgUrl = null;
        this.beyondLimit = 10;
        //消息监听
        wx.onMessage(message => {
            // console.warn("主域发来消息:", message);
            if(message.type == undefined || message.type == "Undefined"){
                console.log("message.type为空");
                return;
            }
            switch(message.type){
                case "friend":
                    // self.beyond.active = false;
                    self.rankList.active = true;
                    self.beyond.parent.active = false;
                    self.showFriend();
                    break;
                case "beyond":
                    self.rankList.active = false;
                    // self.beyond.active = false;
                    self.beyond.parent.active = false;
                    self.updateBeyound(message.level);
                    break;
                case "showBeyond":
                    self.rankList.active = false;
                    self.beyond.parent.active = true;
                    break;
                case "whetherBeyond":
                    self.rankList.active = false;
                    self.beyond.active = false;
                    self.showWhetherBeyond();
                    break;
                case "close":
                    self.rankList.active = false;
                    self.beyond.active = false;
                    self.beyond.parent.active = false;
                    break;
                case "submit":
                    self.submitLevel(message.level,message.beyondLimit);
                    break;
                default:
                    //console.error("发送信息错误!", message.type);
                    self.beyond.active = false;
                    self.rankList.active = false;
                    self.beyond.parent.active = false;
                    break;
            }
        });
        //初始化数据
        this.updateTimer = 0;
        this.lastContentPosY = this.content.y;
        this.bufferZone = (GPool.get("rank", true).height + this.spacing) * this.spawnCount / 2;

        //保存有效好友的数据
        this.friendData = [];
        //玩家自己的信息
        this.selfData = null;
        //头像
        this.friendImg = {};
        //记录玩家自己的名次
        this.myRank = 0;

        this.ranks = [];//排行项数组
        this.getSelfAndFriendData();
    },

    showWhetherBeyond(){
        if(self.gap.string.indexOf("超越中") > -1){//显示超越好友
            self.gap.string = "";
            var tip = cc.instantiate(this.ti);
            tip.parent = cc.director.getScene();
            tip.position = cc.v2(cc.winSize.width/2, cc.winSize.height/2);
            //tip.getChildByName("info").getComponent(cc.Label).string = info.toString();
            tip.setScale(5);
            var show = cc.scaleTo(0.2, 1);
            var fadeOut = cc.fadeOut(1.3);
            var callFunc = cc.callFunc(function(){
                tip.destroy();
            });
            tip.runAction(cc.sequence(show, fadeOut, callFunc));
        }
    },

    loadAvatar(url, sprite,call,caller){
        var self  = this;
        if(this.friendImg[url]){
            sprite.spriteFrame = this.friendImg[url];
            call && call.call(caller)
        }else{
        try{
            cc.loader.load({url: url, type: 'png'}, function (err, texture) {
                if(err){
                    console.error(err.message || err);
                }
                    sprite && (sprite.spriteFrame = new cc.SpriteFrame(texture));
                    self.friendImg[url] = new cc.SpriteFrame(texture);
                    call && call.call(caller)
            });
        }catch(e){
            console.error(e);
                sprite && (sprite.node.active = false);
            }
        }
    },

    //更新超越好友信息
    updateBeyound(level){
        if(this.friendData){
            var friendData = this.getBeyoundData(level);
            if(friendData && friendData.gap <= this.beyondLimit){
                this.renderBeyound(friendData);
                console.warn("超越好友  显示");
            }else{
                this.beyond.active = false;
                if(!friendData){
                    console.warn("超越好友  隐藏  没有拿到超越的好友数据");
                }else if(friendData && friendData.gap > this.beyondLimit){
                    console.warn("超越好友  隐藏  等级差距",level,friendData,this.beyondLimit);
                }else{
                    console.warn("超越好友  隐藏",friendData,this.beyondLimit);
                            }
                        }
        }else{
            this.getSelfAndFriendData(function () {
                var friendData = this.getBeyoundData(level);
                if(friendData && friendData.gap <= this.beyondLimit){
                    this.renderBeyound(friendData);
                    console.warn("超越好友  显示");
                }else{
                    this.beyond.active = false;
                    if(!friendData){
                        console.warn("超越好友  隐藏  没有拿到超越的好友数据");
                    }else if(friendData && friendData.gap > this.beyondLimit){
                        console.warn("超越好友  隐藏  等级差距",level,friendData,this.beyondLimit);
                        }else{
                        console.warn("超越好友  隐藏",friendData,this.beyondLimit);
                    }
                }
            },this,function () {
                this.beyond.active = false;
                console.warn("超越好友  隐藏  获取好友数据失败");
            });
        }
    },
    //渲染即将超越的好友信息
    renderBeyound(friendData){
        var self = this;
        var previousInfo = friendData.friend;
        if(!self.avatar.imgUrl || self.avatar.imgUrl != previousInfo.avatarUrl){
            self.loadAvatar(previousInfo.avatarUrl, self.avatar,function () {
                this.avatar.imgUrl = previousInfo.avatarUrl;
                this.beyond.active = true;
            },this);
        }else if(self.avatar.imgUrl == previousInfo.avatarUrl){
            this.beyond.active = true;
        }
        var gap = friendData.gap;
        var gapInfo = "";
        var beyondHimInfo = "";
        var gapY = 0;
        if(gap === 0){
            gapInfo = "超越中";
            beyondHimInfo = "";
            gapY = -1;
        }else{
            gapInfo = "还有" + gap + "关";
            beyondHimInfo = "超越他!";
            gapY = 14;
        }
        self.gap.string = gapInfo;
        self.gap.node.y = gapY;
        self.beyondHim.string = beyondHimInfo;
    },
    //取得即将超越的好友
    getBeyoundData(level){
        var self = this;
        var userData = this.selfData;
        var overFriendData = null;
        for(var i = self.friendData.length -1 ; i >= 0; i--){
            var previousInfo = self.friendData[i];
            var friendLevel = Number(previousInfo.KVDataList[0].value);
            if(userData.avatarUrl != self.friendData[i].avatarUrl && friendLevel >= level){
                overFriendData = {};
                overFriendData.friend = previousInfo;
                overFriendData.gap = friendLevel - level;
                break;
            }
                            }
        return overFriendData;
    },
    //拉取玩家和好友的信息
    getSelfAndFriendData(call,caller,failCall){
        var self = this;
        wx.getUserInfo({
            openIdList: ["selfOpenId"],
            success(selfData){
                self.selfData = selfData.data[0];
                wx.getFriendCloudStorage({
                    keyList: ["level"],
                    success(res){
                        //将有效数据的好友保存起来并排序
                        self.setFriendData(res.data);
                        for(var i=0;i<self.friendData.length;i++){
                            self.loadAvatar(self.friendData[i].avatarUrl);
                        }
                        call && call.call(caller)
                    },
                    fail(res){
                        failCall && failCall.call(caller)
                    },
                });
            }
        })
    },

    //删除注意移位
    clearContent(){
        this.tips.active = true;
        this.tips.getComponent(cc.Label).string = "努力加载中...";
        this.rankScrollView.scrollToTop(0.1);
        if(this.content.childrenCount > 0){
            var length = this.content.childrenCount;
            for(var i = 0; i < length; i++){
                GPool.put("rank", this.content.children[length - 1 - i]);
            }
        }
    },

    sort(a,b){
        return Number(b.KVDataList[0].value) - Number(a.KVDataList[0].value);
    },

    setFriendData(data){
        this.friendData = [];
        for(var i = 0; i < data.length; i ++){
            if(data[i].KVDataList.length > 0){
                this.friendData.push(data[i]);
            }
        }
        this.friendData.sort(this.sort);
        //console.warn("好友有效数据", this.friendData);
    },

    showFriend(){
        //清理现有数据
        this.clearContent();
        var self = this;
        wx.getUserInfo({
            openIdList: ["selfOpenId"],
            success(selfData){
                var userData = selfData.data[0];
                self.selfData = userData;
                //console.warn("获取玩家自己的数据", userData);
                //取出所有好友数据
                wx.getFriendCloudStorage({
                    keyList: ["level"],
                    success(res){
                        //将有效数据的好友保存起来并排序
                        self.setFriendData(res.data);
                        //console.error("所有数据", res.data);
                        //玩家自己的数据
                        var myData = null;
                        // 获取整个列表的高度
                        self.totalCount = self.friendData.length;
                        self.content.height = (self.totalCount - 3)* (GPool.get("rank", true).height + self.spacing) + self.spacing;
                        //将前三名信息放入大头像
                        for(var m = 1; m < 4; m++){
                            var info = self.friendData[m - 1];
                            var initData = null;
                            if(info){
                                initData = {
                                    avatarUrl: info.avatarUrl,
                                    nickName: info.nickname,
                                    data: Number(info.KVDataList[0].value)
                                }
                                //找寻玩家自己的数据
                                if(userData.avatarUrl == info.avatarUrl){
                                    myData = {
                                        ranking: m,
                                        avatarUrl: info.avatarUrl,
                                        nickName: info.nickname,
                                        data: Number(info.KVDataList[0].value)
                                    };
                                }
                            }
                            self["top" + m].getComponent("top3").init(initData);
                            
                        }
                        //剩下的数据排在下面的普通排行榜里面  最多创建到 spawnCount + 3
                        for(var i = 3; i < self.spawnCount + 3; i++){
                            //超过数据量就停止创建
                            if(i >= self.totalCount){
                                break;
                            }
                            var leftInfo = self.friendData[i];
                            var rankData = {
                                ranking: i + 1,
                                avatarUrl: leftInfo.avatarUrl,
                                nickName: leftInfo.nickname,
                                data: Number(leftInfo.KVDataList[0].value)
                            };
                            var rank = GPool.get("rank");
                            rank.getComponent("rank").init(rankData);
                            rank.parent = self.content;
                            rank.position = cc.v2(0, -rank.height * (0.5 + i - 3) - self.spacing * (i - 3 + 1));
                            self.ranks.push(rank);
                            
                            //找寻玩家自己的数据
                            if(userData.avatarUrl == leftInfo.avatarUrl){
                                myData = {
                                    ranking: i + 1,
                                    avatarUrl: leftInfo.avatarUrl,
                                    nickName: leftInfo.nickname,
                                    data: Number(leftInfo.KVDataList[0].value)
                                };
                            }
                        }
                        //继续找玩家数据
                        if(!myData){
                            for(var a = self.spawnCount + 3; a < self.friendData.length; a++){
                                //找寻玩家自己的数据
                                var infoma = self.friendData[a];
                                if(userData.avatarUrl == infoma.avatarUrl){
                                    myData = {
                                        ranking: a + 1,
                                        avatarUrl: infoma.avatarUrl,
                                        nickName: infoma.nickname,
                                        data: Number(infoma.KVDataList[0].value)
                                    };
                                }
                            }
                        }
                        //玩家自己的数据展示
                        self.rankMine.getComponent("rank").init(myData);
                        self.tips.active = false;
                    },
                    fail(res){
                        self.tips.active = true;
                        self.tips.getComponent(cc.Label).string = "数据加载失败，请检测网络，谢谢";
                    },
                });
            },
            fail(res){
                self.tips.active = true;
                self.tips.getComponent(cc.Label).string = "数据加载失败，请检测网络，谢谢";
            }
        });
    },

    // 返回item在ScrollView空间的坐标值
    getPositionInView(item){
        var worldPos = this.content.convertToWorldSpaceAR(item.position);
        var viewPos = this.rankScrollView.node.convertToNodeSpaceAR(worldPos);
        return viewPos;
    },

    // 每帧调用一次。根据滚动位置动态更新item的坐标和显示(所以spawnCount可以比totalCount少很多)
    update(dt){
        this.updateTimer += dt;
        if (this.updateTimer < this.updateInterval || this.content.childrenCount === 0) {
            return;
        }
        this.updateTimer = 0;
        var items = this.ranks;
        // 如果当前content的y坐标小于上次记录值，则代表往下滚动，否则往上。
        var isDown = this.content.y < this.lastContentPosY;
        // 实际创建项占了多高（即它们的高度累加）
        var offset = (items[0].height + this.spacing) * items.length;
        var newY = 0;

        // 遍历数组，更新item的位置和显示
        for (var i = 0; i < items.length; i++) {
            var viewPos = this.getPositionInView(items[i]);
            if (isDown) {//向下移动
                // 提前计算出该item的新的y坐标
                newY = items[i].y + offset;
                // 如果往下滚动时item已经超出缓冲矩形，
                // 则更新item的坐标（即上移了一个offset的位置），同时更新item的显示内容
                if(viewPos.y < -this.bufferZone && newY < 0){
                    var rank = items[i].getComponent("rank").getRank();
                    var newData = self.friendData[rank - items.length - 1];
                    if(newData){
                        var rankData = {
                            ranking: rank - items.length,
                            avatarUrl: newData.avatarUrl,
                            nickName: newData.nickname,
                            data: Number(newData.KVDataList[0].value)
                        };
                        items[i].getComponent("rank").init(rankData);
                        //更新位置和显示的数据
                        items[i].y = newY;
                    }
                }
            }else{//向上
                // 提前计算出该item的新的y坐标
                newY = items[i].y - offset;
                // 如果往上滚动时item已经超出缓冲矩形，
                // 则更新item的坐标（即下移了一个offset的位置），同时更新item的显示内容
                if(viewPos.y > this.bufferZone && newY > -this.content.height){
                    var rank = items[i].getComponent("rank").getRank();
                    var newData = self.friendData[rank + items.length - 1];
                    if(newData){
                        var rankData = {
                            ranking: rank + items.length,
                            avatarUrl: newData.avatarUrl,
                            nickName: newData.nickname,
                            data: Number(newData.KVDataList[0].value)
                        };
                        items[i].getComponent("rank").init(rankData);
                        //更新位置和显示的数据
                        items[i].y = newY;
                    }
                }
            }
        }

        // 更新lastContentPosY
        this.lastContentPosY = this.content.y;
    },

    submitLevel(level,beyondLimit){
        // 对用户托管数据进行写数据操作
        if (!isNaN(parseInt(level))) {
            wx.setUserCloudStorage({
                KVDataList: [{key: "level", value: "" + level}],
                success: function (res) {
                    console.log('setUserCloudStorage', 'success', res);
                },
                fail: function (res) {
                    console.log('setUserCloudStorage', 'fail', res)
                },
            });
            this.beyondLimit = beyondLimit;
            this.updateBeyound(parseInt(level));
        }
    },

});


